<template>
  <div class="tag-views">
    <view class="tag-list flex-lc">
      <span v-for="item in visitedViews" :key="item.name" @click="togglePage(item)">
        <Tag :color="item.path === activeTag ? 'blue' : 'default'" :closable="closable" @close="closeTag(item)">
          {{ item.title }}
        </Tag>
      </span>
    </view>
  </div>
</template>

<script lang="ts" setup>
import useCachedPageStore from '@/store/cachedPage'
import { Tag } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'

interface RouteType {
  path: string
  name: string
  title: string
}

const route = useRoute()
const router = useRouter()

const activeTag = ref<string>(route.path) //
const visitedViews = ref<RouteType[]>([])

const closable = computed(() => {
  return visitedViews.value.length > 1
})

// 切换标签页
function togglePage(view: RouteType) {
  if (view.path !== activeTag.value) {
    router.push(view.path)
  }
}

// 关闭标签页
function closeTag(page: RouteType) {
  const index = visitedViews.value.findIndex(item => item.name === page.name)
  useCachedPageStore().deleteCachedView(page.name)
  visitedViews.value.splice(index, 1)
  if (page.path === activeTag.value) {
    const preIndex = index > 0 ? index - 1 : index
    router.push(visitedViews.value[preIndex].path)
  }
}

// 切换标签页
function addTags() {
  if (useCachedPageStore().cachedViews.includes(route.name)) {
    return
  }
  visitedViews.value.push({
    path: route.path,
    name: route.name,
    title: route.meta.title,
  })
  useCachedPageStore().addCachedView(route.name)
}

watch(route, () => {
  addTags()
  activeTag.value = route.path
})

onMounted(() => {
  activeTag.value = route.path
  addTags()
})
</script>

<style lang="less" scoped>
.tag-views {
  width: 100%;
  height: 34px;
  padding-top: 6px;
  overflow-x: scroll;
  background: #fff;
  border-bottom: 1px solid #d8dce5;
  box-shadow:
    0 1px 3px 0 rgb(0 0 0 / 12%),
    0 0 3px 0 rgb(0 0 0 / 4%);

  .tag-list {
    padding: 0 10px;

    & > span {
      cursor: pointer;
    }
  }
}
</style>
